const redoBtn = document.getElementById('redo')
const undoBtn = document.getElementById('undo')

// 历史记录栈（存储DOM节点快照）
let history = [editor.cloneNode(true)];
let currentStep = 0;
const MAX_HISTORY = 100;

// 保存编辑器状态
const saveState = () => {
  const snapshot = editor.cloneNode(true);
  history = history.slice(0, currentStep + 1);
  history.push(snapshot);
  currentStep++;
  
  // 内存管理
  if (history.length > MAX_HISTORY) {
    history.shift();
    currentStep = Math.min(currentStep, MAX_HISTORY - 1);
  }
  
  updateButtonStates();
};

// 更新按钮状态
const updateButtonStates = () => {
  redoBtn.enabled = currentStep <= 0
  undoBtn.enabled = currentStep >= history.length - 1
};

// 使用MutationObserver监听变化（带防抖）
const observer = new MutationObserver(() => {
  if (!editor.isEqualNode(history[currentStep])) {
    requestIdleCallback(saveState); // 空闲时段处理
  }
});

observer.observe(editor, {
  childList: true,
  subtree: true,
  characterData: true,
  attributes: true
});


redoBtn.addEventListener('click', () => {
  console.log('redo button');
  if (currentStep < history.length - 1) {
    observer.disconnect();
    currentStep++;
    replaceContent(history[currentStep]);
    updateButtonStates();
    observer.observe(editor, { childList: true, subtree: true, characterData: true, attributes: true });
  }
})


undoBtn.addEventListener('click', () => {
  if (currentStep > 0) {
    observer.disconnect();
    currentStep--;
    replaceContent(history[currentStep]);
    updateButtonStates();
    observer.observe(editor, { childList: true, subtree: true, characterData: true, attributes: true });
  }
})


// 安全替换内容（含选区恢复）
const replaceContent = (newContent) => {
  const selection = window.getSelection();
  const range = document.createRange();
  
  // 清空现有内容
  while (editor.firstChild) editor.removeChild(editor.firstChild);
  
  // 插入新内容
  const fragment = document.createDocumentFragment();
  Array.from(newContent.childNodes).forEach(node => {
    fragment.appendChild(node.cloneNode(true));
  });
  editor.appendChild(fragment);

  // 恢复选区
  try {
    range.setStart(editor, 0);
    range.collapse(true);
    selection.removeAllRanges();
    selection.addRange(range);
  } catch (e) {
    console.error('选区恢复失败');
  }
};

updateButtonStates();
